package com.simdo.g768.Fragment;

import static com.simdo.g768.MainActivity.device;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.g768.Bean.UeidBean;
import com.g768.MessageControl.MessageController;
import com.simdo.g768.Adapter.AutoSearchAdapter;
import com.simdo.g768.Adapter.BlackListSlideAdapter;
import com.simdo.g768.Adapter.HistoryAdapter;
import com.simdo.g768.Bean.GnbBean;
import com.simdo.g768.Bean.HistoryBean;
import com.simdo.g768.Bean.MyUeidBean;
import com.simdo.g768.Dialog.TraceDialog;
import com.simdo.g768.File.FileUtil;
import com.simdo.g768.Listener.ItemClickListener;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.ExcelUtil;
import com.simdo.g768.Util.GsonUtil;
import com.simdo.g768.Util.PrefUtil;
import com.simdo.g768.Util.Util;
import com.simdo.g768.ZApplication;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class CfgTraceChildFragment extends Fragment {

    Context mContext;
    public HistoryAdapter historyAdapter;
    BlackListSlideAdapter blackListAdapter;

    public CfgTraceChildFragment() {
    }
    public CfgTraceChildFragment(Context context) {
        this.mContext = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppLog.I("CatchChildFragment onCreate");
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        AppLog.I("CatchChildFragment onCreateView");

        View view = inflater.inflate(R.layout.child_pager_history, container, false);

        initView(view);
        return view;
    }

    private void initView(View view) {
        RecyclerView rv_history = view.findViewById(R.id.rv_history);
        rv_history.setLayoutManager(new LinearLayoutManager(mContext));
        historyAdapter = new HistoryAdapter(mContext, MainActivity.getInstance().historyList, new ItemClickListener() {
            @Override
            public void onItemClickListener(View v, int position) {
                showHistoryClickWindow(v, position);
            }
        });
        rv_history.setAdapter(historyAdapter);

        view.findViewById(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ZApplication.getInstance().isTrace) showAddSelectWindow(v);
                else {
                    TraceDialog dialog = new TraceDialog(mContext, historyAdapter, -1, false);
                    dialog.show();
                }
            }
        });
        TextView tv_black_list = view.findViewById(R.id.tv_black_list);
        tv_black_list.setText(mContext.getString(ZApplication.getInstance().isTrace || ZApplication.getInstance().isCatch ? R.string.black_list : R.string.white_list));
        tv_black_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBlackListDialog();
            }
        });
        if (ZApplication.getInstance().isCatch) tv_black_list.setVisibility(View.GONE);
    }

    private void showHistoryClickWindow(View v, int position) {
        HistoryBean historyBean = MainActivity.getInstance().historyList.get(position);
        if (historyBean.getMode() > 3) return; // 管控的前面三个默认，不允许操作
        View view = LayoutInflater.from(mContext).inflate(R.layout.popup_history_click_menu, null);
        final PopupWindow popupWindow = new PopupWindow(view, Util.dp2px(mContext, 16 * 6), Util.dp2px(mContext, 40 * 3), true);
        view.findViewById(R.id.tv_edit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                HistoryBean historyBean = MainActivity.getInstance().historyList.get(position);
                if (historyBean.getMode() == 2 || historyBean.getMode() == 3){
                    TraceDialog dialog = new TraceDialog(mContext, historyAdapter, position, false);
                    dialog.show();
                }else showAutoAddDialog(position, historyBean.getImsi());
            }
        });
        view.findViewById(R.id.tv_rename).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();

                showRenameDialog(position);
            }
        });
        view.findViewById(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                historyAdapter.deleteData(position);
            }
        });

        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);

        Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.bg_popup);
        popupWindow.setBackgroundDrawable(drawable);

        popupWindow.showAsDropDown(v, 80, 0);
    }

    private void showAddSelectWindow(View v) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popup_add_menu, null);
        final PopupWindow popupWindow = new PopupWindow(view, Util.dp2px(mContext, 16 * 6), Util.dp2px(mContext, 40 * 2), true);
        view.findViewById(R.id.tv_add_auto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                showAutoAddDialog(0, "");
            }
        });
        view.findViewById(R.id.tv_add_hand).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                TraceDialog dialog = new TraceDialog(mContext, historyAdapter, -1, false);
                dialog.show();
            }
        });

        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);

        Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.bg_popup);
        popupWindow.setBackgroundDrawable(drawable);

        popupWindow.showAsDropDown(v, -50, 10);
    }

    private void hideSoftKeyBoard(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showRenameDialog(int pos){
        HistoryBean historyBean = MainActivity.getInstance().historyList.get(pos);
        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        final AutoCompleteTextView actv_input = view.findViewById(R.id.actv_input);
        actv_input.setText(historyBean.getName());

        view.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = actv_input.getEditableText().toString().trim();

                hideSoftKeyBoard(v);
                if (name.equals(historyBean.getName())){
                    MainActivity.getInstance().closeDialog(dialog);
                }else if (!name.isEmpty()){
                    historyBean.setName(name);
                    MainActivity.getInstance().mDbManage.updateName(historyBean);
                    MainActivity.getInstance().closeDialog(dialog);
                    MainActivity.getInstance().showToast(getString(R.string.update_ok));
                    historyAdapter.notifyDataSetChanged();
                }
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showAutoAddDialog(int pos, String lastImsi){
        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_auto, null);
        final AutoCompleteTextView actv_imsi = view.findViewById(R.id.actv_imsi);
        AutoSearchAdapter dropImsiAdapter = new AutoSearchAdapter(mContext, MainActivity.getInstance().dropImsiList);
        actv_imsi.setAdapter(dropImsiAdapter);
        if (!lastImsi.isEmpty()) actv_imsi.setText(lastImsi);
        view.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String imsi = actv_imsi.getEditableText().toString().trim();
                if (imsi.length() != 15) {
                    MainActivity.getInstance().showToast(getString(R.string.imsi_err_tip));
                    return;
                }
                hideSoftKeyBoard(v);
                if (imsi.equals(lastImsi)){
                    MainActivity.getInstance().closeDialog(dialog);
                    return;
                }else if (!lastImsi.isEmpty()){
                    historyAdapter.updateData(pos, imsi);
                    MainActivity.getInstance().closeDialog(dialog);
                    MainActivity.getInstance().showToast(getString(R.string.imsi_update));
                    return;
                }

                MainActivity.getInstance().addDropImsiList(imsi);

                MainActivity.getInstance().showToast(historyAdapter.addData(0, imsi) ? getString(R.string.added) : getString(R.string.existed));

                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showBlackListDialog() {
        Dialog dialog = MainActivity.getInstance().createDialog(false);
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_blacklist_silde, null);

        TextView tv_black_white = view.findViewById(R.id.tv_black_white);
        tv_black_white.setText(mContext.getString(ZApplication.getInstance().isTrace || ZApplication.getInstance().isCatch ? R.string.black_list : R.string.white_list));
        RecyclerView black_list = view.findViewById(R.id.black_list);
        black_list.setLayoutManager(new LinearLayoutManager(mContext));

        blackListAdapter = new BlackListSlideAdapter(mContext, MainActivity.getInstance().getBlackList(), new BlackListSlideAdapter.ListItemListener() {
            @Override
            public void onItemClickListener(int pos, MyUeidBean bean) {
                if (ZApplication.getInstance().isTrace){
                    if (device != null && device.getWorkState() == GnbBean.State.TRACE){
                        MainActivity.getInstance().checkAndChangeImsi(bean.getUeidBean().getImsi());
                    }else {
                        historyAdapter.addData(1, bean.getUeidBean().getImsi());
                        MainActivity.getInstance().startRunWork();
                    }
                    MainActivity.getInstance().closeDialog(dialog);
                }else {
                    showBlackListCfgDialog(false, pos);
                }
            }
        });
        black_list.setAdapter(blackListAdapter);
        view.findViewById(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBlackListCfgDialog(true, -1);
            }
        });

        view.findViewById(R.id.tv_import).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //Uri uri = Uri.fromFile(new File(FileUtil.build().getSDPath()));
                //设置xls xlsx 2种类型 , 以 | 划分
                intent.setDataAndType(null, "application/vnd.ms-excel|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    intent.putExtra(Intent.EXTRA_MIME_TYPES,
                            new String[]{"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
                } else {
                    intent.setType("application/vnd.ms-excel|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                }
                activityForResult.launch(intent);
            }
        });

        view.findViewById(R.id.tv_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = MainActivity.getInstance().createDialog(false);
                View mView = LayoutInflater.from(mContext).inflate(R.layout.dialog_confirm, null);

                TextView tv_title = mView.findViewById(R.id.tv_title);
                tv_title.setText("清空提示");
                TextView tv_msg = mView.findViewById(R.id.tv_msg);
                tv_msg.setText(mContext.getString(R.string.clear_warning_tip));
                mView.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MainActivity.getInstance().clearBlackList();
                        PrefUtil.build().putString("black_list", "");
                        blackListAdapter.notifyDataSetChanged();
                        MainActivity.getInstance().sendBlackListToDev();
                        MainActivity.getInstance().closeDialog(dialog);
                    }
                });
                mView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MainActivity.getInstance().closeDialog(dialog);
                    }
                });
                MainActivity.getInstance().showDialog(dialog, mView, false);
            }
        });

        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false, true);
    }

    /**
     * 添加黑名单
     */
    private void showBlackListCfgDialog(final boolean isAdd, final int position) {

        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_black_list_cfg, null);

        TextView tv_black_cfg_title = view.findViewById(R.id.tv_black_cfg_title);

        final TextView btn_ok = view.findViewById(R.id.btn_ok);
        final TextView btn_cancel = view.findViewById(R.id.btn_cancel);
        TextView back = view.findViewById(R.id.back);
        final EditText ed_imsi_name = view.findViewById(R.id.ed_imsi_name);
        final AutoCompleteTextView actv_imsi = view.findViewById(R.id.actv_imsi);

        if (isAdd) {
            tv_black_cfg_title.setText(R.string.add_black_title);
            btn_ok.setText(R.string.add);
            btn_cancel.setText(R.string.cancel);
            btn_cancel.setTextColor(Color.parseColor("#666666"));
            back.setVisibility(View.GONE);
        } else {
            tv_black_cfg_title.setText(R.string.edit_black_title);
            btn_ok.setText(R.string.confirm_modify);
            btn_cancel.setText(R.string.delete);
            btn_cancel.setTextColor(Color.RED);
            back.setVisibility(View.VISIBLE);
            if (position != -1) {
                MyUeidBean bean = MainActivity.getInstance().getBlackList().get(position);
                ed_imsi_name.setText(bean.getName());
                actv_imsi.setText(bean.getUeidBean().getImsi());
            }
        }

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String imsi_name = ed_imsi_name.getText().toString();
                String imsi = actv_imsi.getText().toString();
                if (imsi_name.isEmpty() || imsi.isEmpty()) {
                    MainActivity.getInstance().showToast(getString(R.string.data_empty_tip));
                    return;
                }
                if (imsi.length() != 15) {
                    MainActivity.getInstance().showToast(getString(R.string.imsi_err_tip));
                    return;
                }

                MyUeidBean bean;
                if (isAdd) {
                    boolean canAdd = true;
                    for (MyUeidBean bean1 : MainActivity.getInstance().getBlackList()) {
                        if (bean1.getUeidBean().getImsi().equals(imsi)) {
                            canAdd = false;
                            break;
                        }
                    }
                    if (canAdd) {
                        bean = new MyUeidBean(imsi_name, new UeidBean(imsi, ""), false, false);
                        MainActivity.getInstance().getBlackList().add(bean);
                        blackListAdapter.notifyDataSetChanged();
                        MainActivity.getInstance().sendBlackListToDev();
                    } else {
                        MainActivity.getInstance().showToast(getString(R.string.imsi_repeat_tip));
                        return;
                    }
                } else {
                    bean = MainActivity.getInstance().getBlackList().get(position);
                    bean.setName(imsi_name);
                    bean.getUeidBean().setImsi(imsi);
                    MainActivity.getInstance().getBlackList().set(position, bean);
                    blackListAdapter.notifyItemChanged(position);
                    MainActivity.getInstance().showToast(getString(R.string.update_ok));
                }
                PrefUtil.build().putString("black_list", GsonUtil.createJsonString(MainActivity.getInstance().getBlackList()));
                MainActivity.getInstance().sendBlackListToDev();
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_cancel.getText().toString().equals(getString(R.string.delete))) {
                    new AlertDialog.Builder(mContext)
                            .setTitle(R.string.delete_tip_title)
                            .setMessage(R.string.delete_tip)
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int type) {
                                    MainActivity.getInstance().getBlackList().remove(position);
                                    PrefUtil.build().putString("black_list", GsonUtil.createJsonString(MainActivity.getInstance().getBlackList()));
                                    blackListAdapter.notifyDataSetChanged();
                                    MainActivity.getInstance().sendBlackListToDev();
                                    MainActivity.getInstance().closeDialog(dialog);
                                }
                            })
                            .setNegativeButton(R.string.cancel, null)
                            .show();
                } else MainActivity.getInstance().closeDialog(dialog);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    ActivityResultLauncher<Intent> activityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            AppLog.I("SettingFragment onActivityResult result = " + result);
            if (result.getResultCode() == Activity.RESULT_OK) {
                if (result.getData() != null) {
                    AppLog.I("SettingFragment onActivityResult result.getData().getDataString() = " + result.getData().getDataString());
                    String dataString = result.getData().getDataString();
                    if (dataString != null && !dataString.isEmpty()) {
                        String[] split = dataString.split("%");
                        StringBuilder path = new StringBuilder(FileUtil.build().getSDPath());
                        for (int i = 1; i < split.length; i++) {
                            path.append("/");
                            path.append(split[i].substring(2));
                        }

                        //path.deleteCharAt(path.length() - 1);
                        final ProgressDialog progressDialog = new ProgressDialog(mContext, R.style.ThemeProgressDialogStyle);
                        progressDialog.setCanceledOnTouchOutside(false);
                        progressDialog.setCancelable(false);   // 返回键不消失
                        progressDialog.setTitle("正在读取");
                        String message = "正在打开文件";
                        progressDialog.setMessage(message);
                        progressDialog.show();

                        ExcelUtil.readExcel(path.toString(), new ExcelUtil.OnReadProgressListener() {
                            @Override
                            public void onReadProgress(int position) {
                                String message = "当前进度： " + position + "%";
                                MainActivity.getInstance().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.setMessage(message);
                                    }
                                });
                            }

                            @Override
                            public void onReadOk(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount) {
                                String message = "读取完成，正在解析";
                                MainActivity.getInstance().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.setMessage(message);
                                        progressDialog.dismiss();
                                    }
                                });
                                parseReadBlackList(set, allCount, okCount, errCount, reCount);
                            }

                            @Override
                            public void onReadFail(String err) {
                                ExcelUtil.readExcel(mContext, result.getData().getData(), new ExcelUtil.OnReadProgressListener() {
                                    @Override
                                    public void onReadProgress(int position) {
                                        String message = "当前进度： " + position + "%";
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                progressDialog.setMessage(message);
                                            }
                                        });
                                    }

                                    @Override
                                    public void onReadOk(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount) {
                                        String message = "读取完成，正在解析";
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                progressDialog.setMessage(message);
                                                progressDialog.dismiss();
                                            }
                                        });
                                        parseReadBlackList(set, allCount, okCount, errCount, reCount);
                                    }

                                    @Override
                                    public void onReadFail(String err) {
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                MainActivity.getInstance().showToast("数据格式不符合规范，请检查!");
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                }
            } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                //MainActivity.getInstance().showToast("您未选择文件!");
            }
        }
    });

    private void parseReadBlackList(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount){
        set.addAll(MainActivity.getInstance().getBlackList());
        // 转换回List
        MainActivity.getInstance().setBlackList(new ArrayList<>(set));
        StringBuilder sb = new StringBuilder();

        sb.append(getString(R.string.import_all_count)).append("\t").append(allCount).append("\n");
        sb.append(getString(R.string.import_err_count)).append("\t").append(errCount).append("\n");
        sb.append(getString(R.string.import_repeat_count)).append("\t").append(reCount).append("\n");
        sb.append(getString(R.string.import_success_count)).append("\t").append(okCount).append("\n");
        MainActivity.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                blackListAdapter.notifyDataSetChanged();
                MainActivity.getInstance().showRemindDialog(getString(R.string.import_result), sb.toString());
            }
        });

        if (okCount > 0)
            PrefUtil.build().putString("black_list", GsonUtil.createJsonString(MainActivity.getInstance().getBlackList()));
    }

    public int getLastPos() {
        return historyAdapter.getLastPos();
    }

    public void setWorking(boolean b) {
        historyAdapter.setWorking(b);
    }
}